import uvicorn
import atexit
import signal
from best_seller.browser import browser_factory, cookie_manager

from web.routes.crawl import router as crawl_router
from fastapi import FastAPI
from best_seller.services.crawl_svc import crawl_svc


app = FastAPI()
app.include_router(crawl_router, prefix='/routers')


def start_service():
    browser_factory.init()
    cookie_manager.init()
    crawl_svc.init()
    crawl_svc.start_service(background=True)
    uvicorn.run(app, host="0.0.0.0", port=8000)


def shutdown_service():
    crawl_svc.close()
    cookie_manager.close()
    browser_factory.close_all_drivers()


def handler(signum, frame):
    shutdown_service()
    exit(0)


signal.signal(signal.SIGINT, handler)

atexit.register(browser_factory.close_all_drivers)


if __name__ == '__main__':
    start_service()